import Vue from 'vue'
import Router from 'vue-router'
import beforeEachHooks from './beforeEachHooks'
import constantRoutes from './constantRoutes'

Vue.use(Router)

const createRouter = () =>
  new Router({
    routes: constantRoutes,
    linkActiveClass: 'active',
    linkExactActiveClass: 'exact-active',
    scrollBehavior: (to, from, savedPosition) => savedPosition || { x: 0, y: 0 },
  })

const router = createRouter()
Object.keys(beforeEachHooks).forEach(hook => {
  router.beforeEach(beforeEachHooks[hook])
})

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}
router.resetRouter = resetRouter

export default router
